<?php

namespace zhtfrontend\controllers;

use common\components\actions\DeleteAction;
use common\components\extenders\AjaxObject;
use common\components\helpers\Fun;
use common\components\helpers\Tree;
use common\models\datas\Menu;
use doumiaoduo\buildform\BuildForm;
use zhtfrontend\models\datas\Admin;
use zhtfrontend\models\datas\Assignment;
use zhtfrontend\models\datas\AuthItem;
use zhtfrontend\models\datas\Mechanic;
use yii\data\Pagination;
use yii\helpers\ArrayHelper;
use yii\helpers\Json;
use yii\web\BadRequestHttpException;
use yii\web\NotFoundHttpException;
use yii\web\Response;
use yii\widgets\ActiveForm;

class AdminController extends \zhtfrontend\components\bases\BaseController
{
    public function actionIndex()
    {
        $param = \Yii::$app->request->get();
        $pageSize = isset($param['pageSize']) ? $param['pageSize'] : 12;
        $data = Admin::find()->orderBy('id ASC');
        if (!empty($param)) {
            $search_data = array_filter($param);
            if (!empty($search_data['username'])) {
                $data->andWhere(['like', 'username', $search_data['username']]);
            }
            if (!empty($search_data['status'])) {
                if ($search_data['status'] == 2) {
                    $search_data['status'] = 0;
                }
                $data->andWhere(['status' => $search_data['status']]);
            }
            if (!empty($search_data['name'])) {
                $data->andWhere(['like', 'name', $search_data['name']]);
            }
            if (!empty($search_data['roles'])) {
                $data->andWhere(['role' => $search_data['roles']]);
            }
        }
        $pages = new Pagination(['totalCount' => $data->count(), 'pageSize' => $pageSize]);
        isset($param['page']) ? $pages->page = $param['page'] - 1 : 0;
        $model = $data->offset($pages->offset)->limit($pages->limit)->all();

        $array = Fun::asArray($model, ['operate']);

        $auth = \Yii::$app->authManager;//Returns the auth manager for this application.
        $roles = $auth->getRoles();
        return $this->render('index', ['roles' => $roles, 'data' => $array, 'pages' => $pages]);
    }


    public function actionCreate()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        $model = new Admin();
        $model->scenario = 'create';
        //$auth = \Yii::$app->authManager;//Returns the auth manager for this application.
        //$roles = $auth->getRoles();// Returns all roles in the system.@return Role[] all roles in the system. The array is indexed by the role names.
        //$roles = ArrayHelper::map($roles, 'name', 'description');
        /**$mechanic = Mechanic::find()->indexBy('id')->all();
        $tree_mechanic = (new Tree($mechanic))->get_tree_select();
        $mechanic_list = $tree_mechanic; 机构和管理员管理放到机构部分进行实现把*/
        //ajax验证
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        if ($model->load(\Yii::$app->request->post()) && $model->validate()) {
            $model->password = \Yii::$app->security->generatePasswordHash($model->password);
            if ($model->save(false)) {
                //$auth->assign($auth->getRole($model->role), $model->id);//Assigns a role to a user.
                return $this->redirectMessage(\Yii::t('zhtfrontend', '管理员添加成功'), Fun::url(['admin/index']));
            }
        }
        return $this->render('create', ['model' => $model]);// 'mechanic_list' => $mechanic_list
    }

    public function actionUpdate()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        if (\Yii::$app->request->get('id') == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '错误请求'));
        }
        $model = Admin::findOne(\Yii::$app->request->get('id'));
        if ($model == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
       // $auth = \Yii::$app->authManager;
        //$roles = $auth->getRoles();
        /*2018-04-10 end:修角色移除失败bug，不要这样获取role啊，role虽然在这个admin表里部署了一下，但是决定的是在auth_assignment表中$role = $model->role;*/
        //$user_havedroles = $auth->getRolesByUser($model->id);
        /*2018-04-10 end:修角色移除失败bug*/
        $defaultPassword = $model->password;
        $model->password = null;
        $model->scenario = 'update';
       // $roles = ArrayHelper::map($roles, 'name', 'description');
      //  $mechanic = Mechanic::find()->indexBy('id')->all();
       // $tree_mechanic = (new Tree($mechanic))->get_tree_select();
       // $mechanic_list = $tree_mechanic;
//        //ajax验证
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        if ($model->load(\Yii::$app->request->post()) && $model->validate()) {
            /*2018-04-10 end:修角色移除失败bug*/
//            if (!empty($user_havedroles)) {
//                foreach ($user_havedroles as $user_havedrole) {
//                    $auth->revoke($user_havedrole, $model->id);//撤销绑定的角色
//                }
//            }
            /*2018-04-10 end:修角色移除失败bug*/
            if ($model->password == null && $model->save(false)) {
                $model->password = $defaultPassword;
            } else {
                $model->password = \Yii::$app->security->generatePasswordHash($model->password);
            }
            if ($model->save(false)) {
                //$auth->assign($auth->getRole($model->role), $model->id);//Assigns a role to a user.
                return $this->redirectMessage(\Yii::t('zhtfrontend', '管理员信息修改成功'), Fun::url(['admin/index']));
            }
        }
        return $this->render('create', ['model' => $model]);
    }

    public function actionUpdatepass()
    {
        $this->layout = false;
        if (\Yii::$app->request->get('id') == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $model = Admin::findOne(\Yii::$app->request->get('id'));
        if ($model == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }

        $model->scenario = 'updatepass';
        $form = new BuildForm('@app/components/forms/adminPassForm.php');
        $form->loadModel(['admin' => $model]);
        //ajax验证
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'updatepass-form' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        if ($form->loadData(\Yii::$app->request->post()) && $form->validate()) {
            $model->password = \Yii::$app->security->generatePasswordHash($model->newpass);
            if ($model->save(false)) {
                \Yii::$app->user->logout();
                return $this->redirectMessage(\Yii::t('zhtfrontend', '修改成功'), Fun::url(['site/index']));
            }
        }

        return $this->render('updatepass', ['form' => $form->render()]);
    }

    //进行用户的角色分配
    public function actionAssignment(){
        /*
         * 1. 先获取目前这个用户拥有的角色和菜单权限，移动到右侧栏中
         * 2. 左侧栏是未进行分配的角色和菜单权限
         * 3. 箭头实现角色和权限的移动变动
         */
//        $menus = Menu::find()->where(['module'=>'branch'])->indexBy('id')->orderBy('listorder ASC,id ASC')->asArray()->all();
//        $tree = (new Tree($menus))->get_tree_select();
//        var_dump($tree);exit;
        if (\Yii::$app->request->get('id') == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $admin_id = \Yii::$app->request->get('id');

        $auth = \Yii::$app->authManager;
        $model = $this->findModel($admin_id);
        /*2018-04-10 end:修角色移除失败bug，不要这样获取role啊，role虽然在这个admin表里部署了一下，但是决定的是在auth_assignment表中$role = $model->role;*/
//        $user_havedroles = $auth->getRolesByUser($admin_id);
//        $user_havedpermissions = $auth->getPermissionsByUser($admin_id);
//        $haved = [
//            'existed_roles'=>$user_havedroles,
//            'existed_permissions'=>$user_havedpermissions
//        ];
        return $this->render('assignment',[
            'model'=>$model,
        ]);
    }

    //有时间的话独立出去增加扩展新吧
    protected function findModel($id)
    {
        if (($user = Admin::findIdentity($id)) !== null) {
            return new Assignment($id, $user);
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    public function actionAssign($id)
    {
        $items = \Yii::$app->request->post('items', []);
        $model = new Assignment($id);
        $success = $model->assign($items);
        \Yii::$app->response->format=Response::FORMAT_JSON;
        $ajaxObject = new AjaxObject();
        $ajaxObject->content = array_merge($model->getItems(), ['success' => $success]);
        return $ajaxObject;
    }

    public function actionRevoke($id)
    {
        $items = \Yii::$app->request->post('items', []);
        $model = new Assignment($id);
        $success = $model->revoke($items);
        \Yii::$app->response->format=Response::FORMAT_JSON;
        $ajaxObject = new AjaxObject();
        $ajaxObject->content = array_merge($model->getItems(), ['success' => $success]);
        return $ajaxObject;
    }

    public function actions()
    {
        return [
            'delete' => [
                'class' => DeleteAction::className(),
                'modelClass' => Admin::className(),
                'message' => ['success' => '管理员删除成功！'],
                'redirectTo' => 'admin/index',
            ],
        ];
    }
}
